package com.aphrodite.io.comm;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

/**
 * Creates a server that listens to a particular port
 * 
 * @author kentelt
 * 
 */
public class SocketServer extends CommConnection {

	private ServerListener listener;
	private StreamConnectionNotifier notify = null;
	private StreamConnection stream;

	/**
	 * Create a Socket server instance
	 * 
	 * @param port
	 *            The port the server listens on
	 */
	public SocketServer(String port) {
		this.serverPort = port;
	}

	public void disconnect() throws IOException {
		isConnected = false;
		stream.close();
		notify.close();
	}

	public void run() {
		StreamConnectionNotifier notify = null;
		StreamConnection stream;
		try {
			notify = (StreamConnectionNotifier) Connector.open("socket://:" + serverPort);
			isConnected = true;
			for (; isConnected;) {
				// if an incomming connection is found
				stream = notify.acceptAndOpen();
				if (listener != null)
					listener.onDataArrived(stream);
			}
		} catch (IOException e) {
			System.out.println("Could not establish server");
			isConnected = false;
			listener.onError(e.toString());
		}
	}

	public void setListener(ServerListener listener) {
		this.listener = listener;
	}

	public void startServer() throws IOException {
		connect();

	}

	public void stopServer() throws IOException {
		disconnect();
	}

}
